package com.example.li_han.servlet;

import com.example.li_han.pojo.NewsType;
import com.example.li_han.service.NewsTypeService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AddNewsType", value = "/AddNewsType")
public class AddNewsType extends HttpServlet {
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sbuffer = new StringBuilder();
        String s;

        while((s = br.readLine()) != null) {
            sbuffer.append(s);
        }

        String requestBody = sbuffer.toString();
        System.out.println("收到添加分类请求: " + requestBody);

        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 解析JSON数据
            Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
            Map<String, Object> rawData = gson.fromJson(requestBody, mapType);

            if (rawData == null) {
                resultMap.put("code", 500);
                resultMap.put("msg", "请求数据为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 验证必要字段
            if (!rawData.containsKey("typeName")) {
                resultMap.put("code", 500);
                resultMap.put("msg", "分类名称不能为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 创建分类对象
            NewsType newsType = new NewsType();
            newsType.setTypeName(rawData.get("typeName").toString().trim());

            // 设置排序值
            if (rawData.containsKey("sortOrder")) {
                Object sortOrderObj = rawData.get("sortOrder");
                if (sortOrderObj instanceof Double) {
                    newsType.setSortOrder(((Double) sortOrderObj).intValue());
                } else if (sortOrderObj instanceof Integer) {
                    newsType.setSortOrder((Integer) sortOrderObj);
                } else {
                    newsType.setSortOrder(Integer.parseInt(sortOrderObj.toString()));
                }
            } else {
                newsType.setSortOrder(1);
            }

            // 添加分类
            NewsTypeService newsTypeService = new NewsTypeService();
            int result = newsTypeService.addNewsType(newsType);

            if (result > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "添加分类成功");
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "添加分类失败，可能已存在同名分类");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器异常: " + e.getMessage());
        }

        sendResponse(resp, resultMap);
    }

    private void sendResponse(HttpServletResponse resp, Map<String, Object> resultMap) throws IOException {
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}